/*
    使用示例：

        html_____
            <el-button @click="request">request</el-button>
            {{ renderMsg }}

        js_______
            import { msgRenderMixin } from "./msgRenderMixin"
            export default {
                mixins: [msgRenderMixin],
                methods: {
                    request() {
                        this._isRenderEnd = false;

                        // 下面是模拟返回
                        const data = ["alsdjfklasjdf", "91273918723", "ALKDJFLAJSDFLK"];
                        const BEFOR_STR = "BEFOR_STR";
                        this.renderMiddleFn(BEFOR_STR);

                        var i = 0;
                        var timer = setInterval(() => {
                            this._isRenderEnd = i >= data.length;
                            this.renderMiddleFn(BEFOR_STR + data.slice(0, i + 1).join(""));
                            i++;
                            if (i >= data.length - 1) {
                                clearInterval(timer);
                                this.renderMiddleFn(BEFOR_STR + data.slice(0, i + 1).join(""), true)
                            }
                        }, 1000);
                    },
                }
            }
*/


/** 流式渲染信息 */
export const msgRenderMixin = {
    data() {
        return {
            renderMsg: "",
            _renderMiddleMsg: "",
            _renderTimer: null,
            _isRenderEnd: true,
            _isOpenRenderDev: false, // 是否开启开发渲染
        }
    },
    methods: {
        renderMiddleFn(msg, isEnd) {
            if (isEnd) {
                clearInterval(this._renderTimer);
                this._renderTimer = null;
                this._renderMiddleMsg = "";
                if (this._isOpenRenderDev) this.renderMsg = msg;
                else this.renderMsg = "";
            }
            else this.renderMsgFn(msg);
        },
        renderMsgFn(msg) {
            const _endFn = _ => {
                clearInterval(this._renderTimer);
                this._renderTimer = null;
            }
            if (this._isRenderEnd) {
                if (this._renderTimer) _endFn();
                this.renderMsg = "";
                this._renderMiddleMsg = "";
            }
            else {
                this._renderMiddleMsg = msg;
                if (this.renderMsg.length < this._renderMiddleMsg.length) {
                    if (!this._renderTimer) {
                        this._renderTimer = setInterval(() => {
                            this.renderMsg = this._renderMiddleMsg.slice(0, this.renderMsg.length + 1);
                            if (this.renderMsg.length >= this._renderMiddleMsg.length) _endFn()
                        }, 50);
                    }
                }
            }
        }
    }
};